﻿using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace SuiHan.Commons.Conf {
    public static class ConfParser {
        private static readonly Regex CommentPattern = new("^\\s*[#;]");
        private static readonly char[] ConfigSep = { '=' };

        private static bool IsComment(string content) {
            return CommentPattern.IsMatch(content);
        }

        public static ConfData Parse(string file) {
            if (!File.Exists(file)) {
                throw new FileNotFoundException($"文件{file}不存在");
            }

            if (Directory.Exists(file)) {
                throw new FileNotFoundException($"{file}不是文件");
            }

            string content = File.ReadAllText(file);
            string[] contents = content.Split('\n', '\r');
            ConfData cnf = new();
            foreach (string item in contents) {
                string line = item.Trim();
                if (string.Empty.Equals(line) || IsComment(line)) {
                    continue;
                }

                string[] config = line.Split(ConfigSep, 2);
                if (config.Length != 2) {
                    throw new ConfParseException($"配置项: {line} 错误");
                }

                string key = config[0].Trim();
                string value = config[1].Trim();
                if (cnf.ContainsKey(key)) {
                    cnf[key].Add(value);
                }

                cnf.Add(key, new List<string> { value });
            }

            return cnf;
        }
    }
}
